package com.jinyi.wwdeng.ui.permission

import android.os.Handler
import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.permissions.XXPermissions
import com.jinyi.base.base.BaseActivity
import com.jinyi.base.utils.HHLog
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActPermissionBinding
import com.jinyi.wwdeng.ui.permission.adapter.PermissionAdapter
import com.jinyi.wwdeng.ui.tab.TabAct
import com.jinyi.wwdeng.utils.dialog.ScoringCommentDialog
import com.jinyi.wwdeng.utils.dialog.TipsDialog
import com.jinyi.wwdeng.utils.dialog.ScoringDialog
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/16 14:26
 * @Annotation：权限列表
 */
class PermissionAct: BaseActivity() {

    private lateinit var binding: ActPermissionBinding

    //权限列表
    private val mPermissionList = arrayListOf(
        "android.permission.READ_SMS",
        "android.permission.READ_PHONE_STATE",
        "android.permission.READ_CALL_LOG",
        "android.permission.READ_CONTACTS")
    //当前显示的权限
    var mPermissionIndex = 0

    //权限描述列表
    private var mItemAdapter: PermissionAdapter? = null

    override fun getRootView(): View {
        binding = ActPermissionBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setTextTitle(getString(R.string.get_permission))
        setTextTitleGravity(Gravity.CENTER)
        setRightBtnRes(R.mipmap.pic_kefu_black_icon)

        initRecyclerView()
    }

    override fun initListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showScoringDialog()
        }
        //上一个
        binding.lastLayout.setOnClickListener {
            if (mPermissionIndex == 0){
                showToast("没有上一个了")
                return@setOnClickListener
            }
            mPermissionIndex--
            showCurrentPermission()
        }
        //下一个
        binding.nextLayout.setOnClickListener {
            if (mPermissionIndex == mPermissionList.size - 1){
                showToast("没有下一个了，即将进入主页")
                Handler().postDelayed({
                    onIntent(TabAct::class.java)
                    finish()
                }, 1500)
                return@setOnClickListener
            }
            mPermissionIndex++
            showCurrentPermission()
        }
        //拒绝权限
        binding.btnDeny.setOnClickListener {
            showScoringCommentDialog()
        }
        //同意权限
        binding.btnAgree.setOnClickListener {
            val permission = mPermissionList[mPermissionIndex]
            val confirmDialog = TipsDialog(this,object : TipsDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view!!.id == R.id.btnRight){
                        hasRequestPermissions(permission)
                    }
                }
            })
            confirmDialog.setCancelable(true)
            confirmDialog.setCanceledOnTouchOutside(false)
            confirmDialog.show()
            confirmDialog.setTipsTitle(resources.getString(R.string.kind_tips))
            confirmDialog.setTips(resources.getString(R.string.permission_confirm_tips))
            confirmDialog.setButtonDoubleText(resources.getString(R.string.cancel),resources.getString(R.string.ok))
            confirmDialog.setButtonDoubleBackgroundResource(R.drawable.base_circle_frame_e5e6e6,R.drawable.base_circle_fill_9fe76f)
        }
        //已授权
        binding.btnAuthorized.setOnClickListener{
            val permission = mPermissionList[mPermissionIndex]
            XXPermissions.startPermissionActivity(this,permission)
        }
        //被禁止
        binding.btnBanned.setOnClickListener {
            val permission = mPermissionList[mPermissionIndex]
            XXPermissions.startPermissionActivity(this,permission)
        }

    }

    override fun initData() {
        mPermissionIndex = 0
        showCurrentPermission()
    }

    override fun onResume() {
        super.onResume()
        isHasPermissions()
    }

    /* 初始化列表 */
    private fun initRecyclerView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(getContext())
        binding.recyclerView.layoutManager = layoutManager
        this.mItemAdapter = PermissionAdapter(binding.recyclerView)
        this.mItemAdapter!!.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mItemAdapter!!.getItem(position)
            when(childView.id){
                R.id.itemLayout -> {

                }
            }
        }
        binding.recyclerView.adapter = this.mItemAdapter
    }

    /**
     * 显示权限信息
     */
    private fun showCurrentPermission(){
        val curtPermission = mPermissionList[mPermissionIndex]

        val list = arrayListOf<JSONObject>()
        val obj = JSONObject()
        obj.put("title","Why we request your device sms data")
        obj.put("des","{APP name} will read the SMS information in your device, collect and analyze your financial SMS, and realize the assessment of your financial and debt status, so as to decide whether to approve your loan application.\n" +
                " your financial and debt status, so as to decide whether to approve your loan application.\n" +
                curtPermission
        )
        list.add(obj)

        val obj2 = JSONObject()
        obj2.put("title","what you can do")
        obj2.put("des","You can choose to refuse the authorization, which will not affect your continued application for loans on the APP.You can choose to refuse the authorization, which will not affect your continued application for loans on the APP.You can choose to refuse the auhich will not affect your continued application for loans on the APP.\n" +
                "You can choose to refuse the authorization, which will not affectto refuse the authorization, which will not affecttoto refuse the authorization, which will not affectto refuse the authorization\n" +
                "You can choose to refuse the authorization, which will not affectto refuse the authorization, which will not affecttoto refuse the authorization, which will not affectto refuse the authorizationot affectto refuse the authorization\n" +
                "You can choose to refuse the authorization, which will not affectto refuse the authorization, which will not affecttoto refuse the authorization, which will not affectto refuse the authorizationot affectto refuse the authorization\n" +
                curtPermission)
        list.add(obj2)
        this.mItemAdapter!!.data  = list

        binding.ivPermissionIcon.setImageResource(PermissionConfig.getPermissionIcon(curtPermission))
        binding.tvPermissionTitle.text = getString(PermissionConfig.getPermissionTitle(curtPermission))
        isHasPermissions()
    }

    /**
     * 是否申请了允许了当前权限
     */
    private fun isHasPermissions(){
        val permission = mPermissionList[mPermissionIndex]

        //是否已获得权限
        val isGranted = PermissionUtils.isAuthorized(this,permission)
        HHLog.e("$permission>>>>>>>>是否已授权："+isGranted)
        //已获得权限
        if (isGranted){
            showPermissionAuthorized()
            return
        }
        //权限状态：0获取权限成功  1申请权限拒绝, 但是下次申请权限还会弹窗  2申请权限拒绝，并且是永久，不会再弹窗  3默认未请求授权状态
        val authorizeStaus = PermissionUtils.getAuthorizeStaus(this,permission)
        HHLog.e("$permission>>>>>>>>状态：$authorizeStaus")
        //2申请权限拒绝，并且是永久，不会再弹窗
        if (authorizeStaus == 2){
            showPermissionBanned()
            return
        }
        showPermissionNotObtained()
    }

    /**
     * 申请权限
     */
    fun hasRequestPermissions(permission: String){
        PermissionUtils.requestPermission(this,permission,object : PermissionListener{
            override fun requestResult(isFlog: Boolean) {
                HHLog.e("requestResult>>>>>>>>>>>>>>$isFlog")
                if (isFlog){
                    showPermissionAuthorized()
                } else {
                    showPermissionBanned()
                }
            }
        })
    }

    /* 权限请求监听 */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtils.onRequestPermissionsResult(this,requestCode, permissions,grantResults)
    }

    /**
     * 未申请
     */
    private fun showPermissionNotObtained(){
        HHLog.e("${mPermissionList[mPermissionIndex]}——————> 权限未申请")
        binding.defaultLayout.visibility = View.VISIBLE
        binding.btnAuthorized.visibility = View.GONE
        binding.btnBanned.visibility = View.GONE
    }

    /**
     * 已允许
     */
    private fun showPermissionAuthorized(){
        HHLog.e("${mPermissionList[mPermissionIndex]}——————> 权限已允许")
        binding.defaultLayout.visibility = View.GONE
        binding.btnAuthorized.visibility = View.VISIBLE
        binding.btnBanned.visibility = View.GONE
    }

    /**
     * 已拒绝
     */
    private fun showPermissionBanned(){
        HHLog.e("${mPermissionList[mPermissionIndex]}——————> 权限已拒绝")
        binding.defaultLayout.visibility = View.GONE
        binding.btnAuthorized.visibility = View.GONE
        binding.btnBanned.visibility = View.VISIBLE
    }

    // TODO:  测试评星
    private fun showScoringDialog(){
        val scoringDialog = ScoringDialog(this,object : ScoringDialog.IDialogCallback{
            override fun completeScoringCount(count: Int) {
                HHLog.e(">>>>>>>>>>评星数量：$count")
            }
        })
        scoringDialog.show()
    }

    // TODO: wwdeng 测试打分评价
    private fun showScoringCommentDialog(){
        val commentDialog = ScoringCommentDialog(this,object : ScoringCommentDialog.IDialogCallback{
            override fun completeScoringCount(count: Int) {
                HHLog.e(">>>>>>>>>>评星数量：$count")
            }
        })
        commentDialog.show()
    }
}